package cvar;

import java.util.ArrayList;
import java.util.List;

import cvar.io.InputReader;
import cvar.model.LPModel;
import cvar.model.transaction.TransactionModelBuilder;
import cvar.solver.MosekSolver;
import cvar.solver.Result;
import cvar.solver.Solver;

public class Starter {

  private Solver solver_;
  
  public LPModel readAndBuildModel(String hpfcFilePath, String needsFilePath) {
    ArrayList<Double> longHpfc = null;
    ArrayList<Double> longNeeds = null;
//    System.err.print("Reading files...");
    try {
      longHpfc = InputReader.readDoubleFile(hpfcFilePath);
      longNeeds = InputReader.readDoubleFile(needsFilePath);
    } catch (Exception e) {
      e.printStackTrace();
    }
//    System.err.println("   Done!");
//    System.err.print("Compress... ");
    double[] hpfcs = compress(longHpfc, true);
    double[] needs = compress(longNeeds, false);
//    System.err.println("   Done!");
//    System.err.print("Create builder... ");
    TransactionModelBuilder builder = new TransactionModelBuilder(hpfcs, needs);
//    System.err.println("   Done!");
//    System.err.print("Build... ");
    return builder.build();
  }

  public void setSolver(Solver solver) {
    solver_ = solver;
  }

  public Result solve() {
    return solver_.solve();
  }

  public double[] compress(List<Double> longList, boolean average) {
    double[] shortVersion = new double[longList.size() / 4];
    for (int i = 0; i < longList.size() / 4; i++) {
      double sum = 0;
      for (int j = 0; j < 4; j++) {
        sum += longList.get(4 * i + j);
      }
      if (average) {
        sum /= 4;
      }
      shortVersion[i] = sum;
    }
    return shortVersion;
  }
  
  public static void main(String[] args) {
    Starter starter = new Starter();
    LPModel model = starter.readAndBuildModel(args[0], args[1]);
    starter.setSolver(new MosekSolver(model));
    starter.solve();
  }

}
